package com.elitetyc.eliteim.server.handler.impl;

import com.elitetyc.eliteim.common.constant.Constants;
import com.elitetyc.eliteim.common.handler.impl.BaseMsgHandler;
import com.elitetyc.eliteim.common.model.DefaultMsg;
import com.elitetyc.eliteim.common.model.IMUserInfo;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.server.holder.SessionSocketHolder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 登陆消息处理器
 * @Date 2021/9/16 13:37
 */
@Component
@Slf4j
public class PingMsgHandlerImpl extends BaseMsgHandler<DefaultMsg> {


    @Autowired
    private RequestProto.RequestProtocol pong;

    @Override
    public boolean support(int type) {
        return Constants.RequestType.PING==type;
    }

    @Override
    public void handleMsg(ChannelHandlerContext ctx, RequestProto.RequestProtocol source, DefaultMsg msg) {
        final Channel channel = ctx.channel();
        // 接收到客户端ping消息，就更新最新的接收消息时间
        if (channel.hasAttr(IMServerHeartBeatHandler.ATTRIBUTE_KEY_READ_TIME)){
            channel.attr(IMServerHeartBeatHandler.ATTRIBUTE_KEY_READ_TIME).set(System.currentTimeMillis());
            // 回复消息
            channel.writeAndFlush(pong).addListener(future -> {
               if (!future.isSuccess()){
                   // 关闭
                   channel.close();
                   final IMUserInfo userInfo = SessionSocketHolder.getUserInfo((NioSocketChannel) ctx.channel());
                   assert userInfo != null;
                   log.error("pong msg error for user id:{} name{} ",userInfo.getUserId(),userInfo.getUserName());
               }
            });
        }

    }


}

